package com.bjtech.web.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Date Utility Class
 * This is used to convert Strings to Dates and TimestampsO
 */
public class DateUtil {
    //~ Static fields/initializers =============================================

    private static Log log = LogFactory.getLog(DateUtil.class);
    private static String defaultDatePattern = "yyyy-MM-dd";
    private static String timePattern = "HH:mm";

    //~ Methods ================================================================
    public static String getDatePattern() {
        return defaultDatePattern;
    }
    
    public static String getDateTimePattern() {
        return DateUtil.getDatePattern() + " HH:mm:ss.S";
    }
    
    public static String getYear() {
		return getDateTime("yyyy",new Date());
	}

	public static String getMonth() {
		return getDateTime("MM",new Date());
	}

	public static String getDate() {
		return getDateTime("yyyy-MM-dd",new Date());
	}

    public static final String getDate(Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }
    
    public static Date getNextTimeByMinute(int minute) {
		Calendar cal = new GregorianCalendar();
		cal.add(Calendar.MINUTE, minute);

		return cal.getTime();
	}
    
    public static Date getNextTimeByDay(int day) {
		Calendar cal = new GregorianCalendar();
		cal.add(Calendar.DAY_OF_YEAR, day);

		return cal.getTime();
	}
    
    public Date setTaskTimer(int dayAmount,int hour,int min){
    	Calendar cal = new GregorianCalendar();
		cal.add(Calendar.DATE,dayAmount);
		cal.set(Calendar.HOUR_OF_DAY,hour);
		cal.set(Calendar.MINUTE,min);
		cal.set(Calendar.SECOND,0);
		return cal.getTime();
	}
    
    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @see java.text.SimpleDateFormat
     * @throws ParseException
     */
    public static final Date convertStringToDate(String aMask, String strDate)
      throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(aMask);

        if (log.isDebugEnabled()) {
            log.debug("converting '" + strDate + "' to date with mask '"
                      + aMask + "'");
        }

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            //log.error("ParseException: " + pe);
            throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }

        return (date);
    }

    /**
     * This method returns the current date time in the format:
     * MM/dd/yyyy HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return getDateTime(timePattern, theTime);
    }

    /**
     * This method returns the current date in the format: MM/dd/yyyy
     * 
     * @return the current date
     * @throws ParseException
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }

    /**
     * This method generates a string representation of a date's date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * 
     * @see java.text.SimpleDateFormat
     */
    public static final String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
            log.error("aDate is null!");
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     * 
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static final String convertDateToString(Date aDate) {
        return getDateTime(getDatePattern(), aDate);
    }

    /**
     * This method converts a String to a date using the datePattern
     * 
     * @param strDate the date to convert (in format MM/dd/yyyy)
     * @return a date object
     * 
     * @throws ParseException
     */
    public static Date convertStringToDate(String strDate)
      throws ParseException {
        Date aDate = null;

        try {
            if (log.isDebugEnabled()) {
                log.debug("converting date with pattern: " + getDatePattern());
            }

            aDate = convertStringToDate(getDatePattern(), strDate);
        } catch (ParseException pe) {
            log.error("Could not convert '" + strDate
                      + "' to a date, throwing exception");
            pe.printStackTrace();
            throw new ParseException(pe.getMessage(),
                                     pe.getErrorOffset());
                    
        }

        return aDate;
    }
    
    public static int getIntervalDaysOfExitDate(Date exitDateFrom, Date exitDateTo){
        Calendar cal_start = Calendar.getInstance();
        cal_start.setTime(exitDateFrom);
        int yearFrom = cal_start.get(Calendar.YEAR);
        int dayFrom = cal_start.get(Calendar.DAY_OF_YEAR);
        Calendar cal_to = Calendar.getInstance();
        cal_to.setTime(exitDateTo);
        int dayTo = cal_to.get(Calendar.DAY_OF_YEAR);
        int yearTo = cal_to.get(Calendar.YEAR);
        if(yearTo==yearFrom){
        	return dayTo - dayFrom;
        }else if(yearTo>yearFrom){
    	  int days = 0;
          while(cal_start.before(cal_to)){
              days++;
              cal_start.add(Calendar.DAY_OF_YEAR, 1);
          }
          return days;
        }else{
        	return 0;
        }
    }
    
    public static void main(String[] args){
    	Calendar c1 = Calendar.getInstance();
    	c1.set(2012, 1, 1);
    	Calendar c2 = Calendar.getInstance();
    	c2.set(2011, 10, 1);
    	System.out.println(getIntervalDaysOfExitDate(c2.getTime(),c1.getTime()));
    }
}
